<template>
  <div
    v-loading="createProjectLoading"
    class="template-preview-container"
  >
    <div class="header">
      <el-page-header
        :content="$t('project.myTemplate.templateDetail')"
        @back="$router.back(-1)"
      />
    </div>
    <div class="template-preview-content t-form-theme-wrap">
      <biz-project-form
        v-if="formConfig.formKey"
        :form-config="formConfig"
        @submit="submitForm"
        class="mb20"
      />
      <div class="use-btn">
        <el-button
          type="primary"
          @click="createProjectByTemplate"
        >
          {{ $t("project.myTemplate.useTemplate") }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import BizProjectForm from "@/views/formgen/components/BizProjectForm/index.vue";
import { useTemplateCreateFormRequest } from "@/api/project/template";
import { FormConfigType, getDefaultFormConfig } from "@/views/formgen/components/GenerateForm/types/form";

const router = useRouter();
const route = useRoute();

const createProjectLoading = ref(false);
const formConfig = ref<FormConfigType>({
  ...getDefaultFormConfig(),
  formKind: 2,
  formBtns: true
});

onMounted(() => {
  formConfig.value.formKey = route.query.key as string;
});

const createProjectByTemplate = async () => {
  createProjectLoading.value = true;
  try {
    const res = await useTemplateCreateFormRequest({ formKey: formConfig.value.formKey });
    if (res.data) {
      router.push({
        path: "/project/form/editor/index",
        query: { key: res.data, active: 1 }
      });
    }
  } catch (error) {
    console.error(error);
  } finally {
    createProjectLoading.value = false;
  }
};

const submitForm = () => {};
</script>

<style lang="scss" scoped>
.template-preview-container {
  width: 100%;
  height: 100%;
}

.header {
  padding: 20px;
}

.template-scrollbar {
  height: 100%;
}

.template-preview-content {
  position: relative;
  background-color: var(--el-bg-color-page);
  height: 100%;

  .use-btn {
    position: absolute;
    top: 50px;
    right: 180px;
  }
}

:deep(.project-form) {
  overflow-y: scroll;
  height: 90%;
}

:deep(.project-form-wrapper) {
  overflow: hidden;
  height: 100%;
}
</style>
